package com.citywithincity.crypt;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AesCrypt implements ICrypt {
	private static final String AESTYPE = "AES/ECB/PKCS5Padding";

	@Override
	public String encrypt(String data, String key) {
		try {
			byte[] encrypt = null;
			Key keySpec =  new SecretKeySpec(key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			encrypt = cipher.doFinal(data.getBytes("UTF-8"));
			return Base64.encodeBase64String(encrypt);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String decrypt(String data, String key) {
		try {
			byte[] bytes = Base64.decodeBase64(data);
			Key cKey = new SecretKeySpec(key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance(AESTYPE);
			cipher.init(Cipher.DECRYPT_MODE, cKey);
			byte[] decrypt = cipher.doFinal(bytes);
			return new String(decrypt,"UTF-8").trim();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


}
